<template>
  <div>
    <h2 style="padding-left: 20px;">随机密码生成器</h2>
    <div class="container random-password-generator">
      <div class="input-group">
        <label for="length">密码长度: </label>
        <input type="number" id="length" v-model.number="passwordLength" min="6" class="input-field" />
      </div>
      <div class="input-group">
        <label class="checkbox-label">
          <input type="checkbox" v-model="includeSpecialCharacters" class="checkbox-input" /> 包含特殊字符
        </label>
      </div>
      <button @click="generatePassword" class="execute-button">生成</button>
      <div v-if="generatedPassword" class="password-output">
        <p class="password-text">{{ generatedPassword }}</p>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue';

export default defineComponent({
  name: 'RandomPasswordGenerator',
  setup() {
    const passwordLength = ref(8); // 默认密码长度为8
    const generatedPassword = ref('');
    const includeSpecialCharacters = ref(true); // 默认包含特殊字符

    // 根据是否包含特殊字符，选择不同的字符集
    const baseCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    const specialCharacters = '!@#$%^&*()_+[]{}|;:,.<>?';
    const getCharacterSet = () => includeSpecialCharacters.value? baseCharacters + specialCharacters : baseCharacters;

    const getRandomCharacter = () => {
      const characters = getCharacterSet();
      return characters.charAt(Math.floor(Math.random() * characters.length));
    };

    const generatePassword = () => {
      generatedPassword.value = '';
      for (let i = 0; i < passwordLength.value; i++) {
        generatedPassword.value += getRandomCharacter();
      }
      copyPassword();
    };

    // 新增复制密码函数
    const copyPassword = () => {
      const textarea = document.createElement('textarea');
      textarea.value = generatedPassword.value;
      document.body.appendChild(textarea);
      textarea.select();
      document.execCommand('copy');
      document.body.removeChild(textarea);
      //alert('密码已复制到剪贴板');
    };

    return {
      passwordLength,
      generatedPassword,
      includeSpecialCharacters,
      generatePassword,
      copyPassword, // 将复制密码函数返回，使其在模板中可用
    };
  },
});
</script>

<style lang="scss" scoped>
@use "../assets/common.scss";

.random-password-generator {
  margin: 20px;
  width: 350px;
}

.input-group {
  margin-bottom: 20px;
  text-align: left;
}

.input-field {
  width: calc(100% - 100px);
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  box-sizing: border-box;
  font-size: 16px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.checkbox-input {
  margin-right: 10px;
}

.password-output {
  margin-top: 20px;
  text-align: left;
}

.password-text {
  font-size: 18px;
  font-family: monospace;
  background-color: #eee;
  padding: 10px;
  border-radius: 5px;
  word-wrap: break-word; /* 防止长密码溢出 */
  text-align: center;
}
</style>